package fserv.model;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author arthur
 */
public class ServerData {

	private static ServerData instance = null;

	private static String dataDir ="";

  /**
   * A map linking every local file to their name
   */
  private Map<String, ServerFile> files = new HashMap<String, ServerFile>();

	/**
	 * @return the dataDir
	 */
	public static String getDataDir() {
		return ServerData.dataDir;
	}

	/**
	 * @param aDataDir the dataDir to set
	 */
	public static void setDataDir(String aDataDir) {
		ServerData.dataDir = aDataDir;
	}

	private ServerData() {
    Logger.getLogger(ServerData.class.getName()).log(Level.INFO, 
            "Using {0} as data directory.", ServerData.dataDir);
    
    if(dataDir.isEmpty())
      throw new RuntimeException("Data directory is not set");
		
    File dataDirFile = new File(dataDir);
    if(!dataDirFile.isDirectory())
      throw new RuntimeException("The specified Data directory is not a directory");

    for(File child : dataDirFile.listFiles()) {
      if(child.isFile()) {
        ServerFile tmp = new ServerFile(child);
        files.put(tmp.getName(), tmp);
      }
    }
	}

	public static ServerData getInstance() {
		if(ServerData.instance == null)
			ServerData.instance = new ServerData();
		return ServerData.instance;
	}

  public synchronized String list() {
    String list = "";

    for(ServerFile f : files.values())
      list += f.getName() + "\n";

    return list;
  }
}
